package com.liruo.learn.spring.mvc.enumconverter.jacksondeprecated;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.liruo.learn.spring.mvc.enumconverter.SourceEnum;

import java.io.IOException;
public class ToEnumJsonDeserializer<S, T extends SourceEnum<S>> extends JsonDeserializer<T> {
    private final Class<T> enumClazz;
    public ToEnumJsonDeserializer(Class<T> enumClazz) {
        this.enumClazz =  enumClazz;
    }
    @Override
    public T deserialize(JsonParser jp, DeserializationContext ctx) throws IOException {
        JsonToken currentToken = jp.getCurrentToken();
        Object source = null;
        switch (currentToken){
            case VALUE_STRING -> source = jp.getText();
            case VALUE_NUMBER_INT -> source = jp.getIntValue();
        }
        for (T enumeration : enumClazz.getEnumConstants()){
            if(enumeration.getSource().equals(source)){
                return enumeration;
            }
        }
        throw new IllegalArgumentException(
                "has not the enumeration source[class="
                        + ((currentToken == JsonToken.VALUE_STRING) ? String.class.getName() : Integer.class.getName())
                        + "] value=" + source);
    }
}